<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CROSControlMiddle
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $hosts = env("REQUEST_PASS_HOST");
        if (empty($hosts)) {
            header("Access-Control-Allow-Origin: *");
        } else {
            $passHost = explode(',', env("REQUEST_PASS_HOST"));
            $fromHost = $request->header("Origin");
            if (in_array($fromHost, $passHost)) {
                header("Access-Control-Allow-Origin: {$fromHost}");
            }

        }
        return $next($request);
    }
}
